package com.conduit.comnands;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.conduit.WinReg.WindowsReqistry;
import com.conduit.commands.prototype.AbstractCommand;
import com.conduit.enums.ResultCode;

public class ValidateRegistryKeyExistsCommand extends AbstractCommand {

	public ValidateRegistryKeyExistsCommand() {
		// validate registry key exists <reg_value> <reg_key> <true/false>
		commandSyntax = "validate registry key exists\\s{2,}(.*)\\s{2,}(.*)\\s{2,}(.*)";
	}

	@Override
	public void executeWithArgs(String args) {
		// validate command syntax
		if (!args.matches(commandSyntax)) {
			setResult("Error in Command's syntax (\"" + args + "\")");
			setResultCode(ResultCode.Error);
			return;
		}
		// get commnad's arguments
		Matcher matcher = Pattern.compile(commandSyntax).matcher(args);
		if (matcher.find()) {
			String regKey = matcher.group(1).trim();
			String regValue = matcher.group(2).trim();
			boolean isExist = Boolean.parseBoolean(matcher.group(3).trim()
					.toLowerCase());
			// get expected value from command
			// get actual result
			try {
				WindowsReqistry.readRegistry(regKey, "\"" + regValue + "\"");
				// if registry key was found and expected to be found
				if (isExist) {
					setResult("Registry Value " + regValue + " Registry Key: "
							+ regKey + " Was found as Expected");
					setResultCode(ResultCode.Successes);
				} else { // if found but was not expected to be found
					setResult("Registry Value " + regValue + " Registry Key: "
							+ regKey + " Was Found not as Expected");
					setResultCode(ResultCode.Error);
				}
				/*
				 * if registry query did not find any value an exception will be
				 * thrown in this case it means that the registry value was not
				 * found
				 */
			} catch (Exception e) {
				if (!isExist) {
					setResult("Registry Value " + regValue + " Registry Key: "
							+ regKey + " Was not found as Expected");
					setResultCode(ResultCode.Successes);
				} else { // if found but was not expected to be found
					setResult("Registry Value " + regValue + " Registry Key: "
							+ regKey + " Was not Found not as Expected");
					setResultCode(ResultCode.Error);
				}
			}
		}
	}

	@Override
	public String getCommandName() {
		// TODO Auto-generated method stub
		return "Validate Registry Key Exists";
	}
}